<!--
 * @file 登录
 * @author its-wild(https://gitee.com/its-wild)
 * @date 2022/02/18
-->
<template>
  <login-container>
    <div class="login">
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="密码登录"></a-tab-pane>
        <a-tab-pane key="2" tab="短信验证码登录"></a-tab-pane>
      </a-tabs>
      <a-form
        ref="formRef"
        :model="formState"
        name="basic"
        autocomplete="off"
        @finish="onFinish"
        class="login-form"
      >
        <a-form-item
          name="mobile"
          :rules="[
            { required: true, message: '请输入手机号！' },
            {
              pattern: /^1[\d]{10}$/,
              message: '请输入正确的手机号！',
              trigger: 'change'
            }
          ]"
        >
          <a-input
            v-model:value="formState.mobile"
            placeholder="请输入手机号"
            size="large"
          >
            <template #prefix>
              <mobile-outlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item
          v-if="activeKey === '1'"
          name="password"
          :rules="[{ required: true, message: '请输入密码！' }]"
        >
          <a-input-password
            v-model:value="formState.password"
            placeholder="请输入密码"
            size="large"
          >
            <template #prefix>
              <lock-outlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item v-if="activeKey === '1'" name="remember">
          <a-checkbox v-model:checked="formState.remember">记住密码</a-checkbox>
        </a-form-item>

        <a-form-item
          v-if="activeKey === '2'"
          name="vcCode"
          :rules="[{ required: true, message: '请输入短信验证码！' }]"
        >
          <a-input
            v-model:value="formState.vcCode"
            placeholder="请输入短信验证码"
            size="large"
            class="img-vcCode-input"
          >
            <template #prefix>
              <mail-outlined />
            </template>
            <template #suffix>
              <a-button type="link" @click="getCodeMSG">{{
                sendBtnText
              }}</a-button>
            </template>
          </a-input>
        </a-form-item>

        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            class="login-form-button"
            size="large"
            :loading="loading"
          >
            登录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </login-container>
</template>
<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/store/user'
import {
  MobileOutlined,
  LockOutlined,
  MailOutlined
} from '@ant-design/icons-vue'
import { local } from '@/plugins/storage'
import {
  ICode,
  loadVerifyCode,
  ILogin,
  IUser,
  // login, // 真实要用的
  sms
} from '@/apis/login'
import LoginContainer from './LoginContainer.vue'

export default defineComponent({
  name: 'Login',
  components: {
    LoginContainer,
    MobileOutlined,
    LockOutlined,
    MailOutlined
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const store = useUserStore()

    const activeKey = ref('1')
    const formRef = ref()

    // 登录按钮加载状态
    const loading = ref(false)
    const setLoading = (value: boolean) => {
      loading.value = value
    }

    // 短信验证码
    const codeMsg = reactive<ICode>({
      key: ''
    })
    const setCodeMSG = (obj: ICode) => {
      codeMsg.key = obj.key
    }

    const afterLogin = (res: IUser) => {
      // 登录成功后存用户
      local.set('user', res)
      store.setUser(res)
      const { rdurl } = route.query
      // 如果地址上有重定向地址则跳转去重定向的地址
      if (rdurl) {
        const queryToken = `token=${res.token}`
        let url = ''
        if (rdurl.includes('?')) {
          url = `${rdurl}&${queryToken}`
        } else {
          url = `${rdurl}?${queryToken}`
        }
        window.location.replace(url)
      } else {
        router.replace({ name: 'home' })
      }
    }

    // 表单数据
    interface FormState {
      mobile: string
      password: string
      remember: boolean
      vcCode: string
    }
    const formState = reactive<FormState>({
      mobile: '',
      password: '',
      remember: true,
      vcCode: ''
    })

    // 登录
    const doLogin = async () => {
      const values: FormState = formRef.value.getFieldsValue()
      // 密码登录
      if (activeKey.value === '1') {
        try {
          const formData: ILogin = {
            mobile: values.mobile,
            password: values.password
          }

          setLoading(true)
          // const res = await login(formData) // 真实的要从接口拿
          const res = {
              uid: '482012',
              account: '75adc',
              name: '张三',
              mobile: '152*****5801',
              email: '',
              loginTime: '2022-11-26 15:36:09',
              regTime: '2021-05-18 09:38:32',
              avatarStoreId: '0',
              gender: 'NONE',
              realName: '老宋',
              userRelations: [
                {
                  id: '1482958425167089665',
                  type: 11,
                  userId: '482012',
                  extId: '0',
                  enable: 1,
                  createTime: '2022-01-17 14:10:10',
                  updateTime: '2022-01-17 14:10:10'
                }
              ],
              token:
                'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb2RlIjoiNDgyMDEyOjk6MjA0RTJBRTdFRkVBNDRBRDhENjNENzNDNDdBN0Q3M0QifQ.MXUu5GmCol94xIunLZle5wPuWKhc0fofAByi2UwOpCs',
              sid: '204E2AE7EFEA44AD8D63D73C47A7D73D'
            }
          if (res) {
            // 记住密码
            if (values.remember) {
              local.set(
                'rememberPsw',
                {
                  mobile: formData.mobile,
                  password: values.password
                },
                null,
                true
              )
            } else {
              local.remove('rememberPsw')
            }
            afterLogin(res)
          }
          setLoading(false)
        } catch (error) {
          setLoading(false)
        }
      } else {
        try {
          const formData = {
            mobile: values.mobile,
            vcCode: values.vcCode
          }
          setLoading(true)
          const res = await sms(formData)
          afterLogin(res)
          setLoading(false)
        } catch (error) {
          setLoading(false)
        }
      }
    }

    // 当点登录并校验成功时
    const onFinish = () => {
      doLogin()
    }

    /**
     * 查看一下上一次是否记住密码
     */
    const isRememberPsw = () => {
      interface IRmb {
        mobile?: string
        password?: string
      }
      const rememberPsw = local.get('rememberPsw', {}, true) as IRmb
      const { mobile, password } = rememberPsw
      if (mobile && password) {
        formState.password = password
        formState.mobile = mobile
      }
    }

    // 发送按钮文字
    const sendBtnText = ref('获取短信验证码')
    const setSendBtnText = (value: string) => {
      sendBtnText.value = value
    }
    // 是否发送短信了
    const sent = ref(false)
    const setSent = (value: boolean) => {
      sent.value = value
    }
    /**
     * 倒计时函数
     */
    const countDown = () => {
      let wait = 60
      setSent(true)
      setSendBtnText(wait + '秒后重发')
      const timer = setInterval(() => {
        wait--
        if (wait <= 0) {
          setSent(false)
          setSendBtnText('重新发送')
          wait = 60
          clearInterval(timer)
        } else {
          setSendBtnText(wait + '秒后重发')
        }
      }, 1000)
    }

    /**
     * 获取短信验证码
     */
    const getCodeMSG = () => {
      // 如果验证码在发送的一分钟内
      if (sent.value) return
      formRef.value.validateFields('mobile').then(async (values: FormState) => {
        const data = {
          param: {
            mobile: values.mobile
          },
          type: 'SMS_VERIFY_CODE_V2'
        }
        try {
          const res = await loadVerifyCode(data)
          if (res && res.key) {
            setCodeMSG(res)
            countDown()
          }
        } catch (error) {
          console.log(error)
        }
      })
    }

    // 处理记住密码
    isRememberPsw()

    return {
      activeKey,
      formRef,
      loading,
      formState,
      onFinish,
      sendBtnText,
      countDown,
      getCodeMSG
    }
  }
})
</script>

<style scoped lang="less">
.login {
  position: relative;
  width: 511px;
  height: 441px;
  background: #fff;
  display: inline-block;
  padding: 25px 50px;
  box-sizing: border-box;
  margin: 88px 0 91px 600px;
  border-radius: 4px;
  text-align: left;
  border-top: 3px solid @primary-color;
  border-top-left-radius: 0px;
  border-top-right-radius: 0px;

  :deep(.ant-tabs-tab) {
    .ant-tabs-tab-btn {
      font-size: 16px;
    }
  }

  :deep(.ant-tabs-tab-active) {
    .ant-tabs-tab-btn {
      font-size: 16px;
      color: #000;
    }
  }

  :deep(.ant-tabs-top) {
    .ant-tabs-nav::before {
      border-color: transparent;
    }
  }

  :deep(.ant-input-affix-wrapper) {
    .ant-input-prefix,
    .ant-input-suffix {
      color: #c0c4cc;
    }
    /**
    * 解决 input:-internal-autofill-selected 带的background-color
    */
    input:-webkit-autofill {
      box-shadow: 0 0 0 1000px #fff inset;
    }
  }

  .img-vc-input {
    padding-top: 0;
    padding-bottom: 0;
  }

  .img-vc {
    height: 40px;

    img {
      height: 100%;
    }
  }

  .login-form-button {
    width: 100%;

    &[disabled],
    &[disabled]:hover,
    &[disabled]:focus,
    &[disabled]:active {
      background: #f5f5f5;
      border-color: #d9d9d9;
    }
  }
}
</style>
